﻿using lib472.API;
using libedi.API;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace libedi
{
    public class Upload
    {

        public async Task<string> upFileAsync(string FilePath)
        {

            string filePath = FilePath; // 修改为您要上传的文件路径
            string apiUrl = $"{Clientbuss.ApiUrl}/api/Edi/PubUploaddbFile"; // 修改为您的 API URL

            using (var client = new HttpClient())
            using (var form = new MultipartFormDataContent())
            {
                // 读取文件内容
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                var fileContent = new StreamContent(fileStream);

                // 设置文件内容的类型（可选）
                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                form.Add(fileContent, "file", Path.GetFileName(filePath)); // "file" 是 API 中接收的参数名


                try
                {
                    // 上传文件
                    var response = await client.PostAsync(apiUrl, form);
                    response.EnsureSuccessStatusCode();

                    string data= await response.Content.ReadAsStringAsync();

                    var item = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
                    return item["fileName"];

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error uploading file: " + ex.Message);
                    return string.Empty;
                }
                finally
                {
                    fileStream.Close(); // 确保流被关闭
                }
            }
        }
    }
}
